package com.the_ring.chapter13.server;


import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/testWebSocket")
public class WebSocketServer {
    // 存放每个客户端对应的 WebSocket 对象
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    private Session session;   // 当前连接会话

    // 连接成功后调用
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocket连接成功");
        this.session = session;
        webSocketSet.add(this);
    }

    // 连接关闭后调用
    @OnClose
    public void onClose() {
        System.out.println("WebSocket连接关闭");
        webSocketSet.remove(this);
    }

    // 连接异常时调用
    @OnError
    public void onError(Throwable error) {
        System.out.println("WebSocket连接异常");
        error.printStackTrace();
    }

    // 收到客户端消息时调用
    @OnMessage
    public void onMessage(String msg) throws IOException {
        System.out.println("接收到客户端消息：" + msg);
        for (WebSocketServer item : webSocketSet) {
            item.session.getBasicRemote().sendText("我听到消息啦 “" + msg + "“ ");
        }
    }
}
